import { Component, OnInit, OnDestroy } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import { NodeNameComponent } from './node-name.component/index';
import { TreeData } from '../../tree-data';
import { TreeViewService } from '../../treeview.service';

@Component({
  selector: 'node-entry',
  // moduleId: module.id,
  templateUrl: 'app/tree-node.component/node-entry.component/tpl.html',
  styleUrls: ['app/tree-node.component/node-entry.component/style.css'],
  inputs: ['treeData'],
  directives: [NodeNameComponent]
})
export class NodeEntryComponent implements OnInit, OnDestroy {
  public treeData: TreeData;
  public foldStatus: string;
  selected: boolean = false;
  foldChange: Observable<boolean>;

  constructor(private _treeService: TreeViewService) {
  }

  ngOnInit() {
    // this.foldStatus = this.treeData.expand? 'expanded': 'folded';
    // console.log(this.foldStatus);
    // if (!this.treeData.hasChildren()) {
    //   this.foldStatus = 'noChildren';
    // }
    this.foldChange = this._treeService.foldForId(this.treeData.id);
    this.foldChange.subscribe(status => {
      this.foldStatus = status? 'expanded': 'folded';
      if (!this.treeData.hasChildren()) {
        this.foldStatus = 'noChildren';
      };
    })
    this._treeService.currentSelection.subscribe(id => {
      if (this.treeData) {
        this.selected = (id === this.treeData.id);
      }
    });
  }

  ngOnDestroy() {
    // console.log('destroy node entry');
    //TODO 注销observeable的订阅
    // this._treeService.currentSelection.unsubscribe();
    // this.foldChange.
  }

  onFoldToggle() {
    this._treeService.foldToggle(this.treeData.id);
  }
  //   if (this.foldStatus !== 'noChildren') {
  //     if (this.treeData.expand) {

  //     }
  //   }
  //   switch (this.treeData.foldStatus) {
  //     case 'expanded':
  //       this.foldStatus = 'folded';
  //       break;
  //     case 'folded':
  //       this.foldStatus = 'expanded';
  //       break;
  //     case 'noChildren':
  //       // do nothing
  //       break;
  //     default:
  //   }
  // }
}